import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:kq_flutter_core_widget/extentions/kq_extentions.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_filed_utils.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_decoration.dart';
import 'package:kq_flutter_core_widget/widgets/shadow/kq_box_shadow.dart';

import '../../resources/kq_pad_theme_colors.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_pad_divider.dart';
import '../textFiled/kq_pad_textfiled.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 输入组件
///
/// [ItemType.edit]
///
/// @author 周卓
///
/// 结合 KqPadFormEntity 使用
class KqPadEditItemView extends StatefulWidget {
  /// 通用属性
  final KqPadFormEntity entity;

  /// 输入控件或选择控件的左侧控件
  final Widget Function(KqPadFormEntity entity)? customLeftView;

  /// 输入控件或选择控件或自定义控件的右侧控件
  final Widget Function(KqPadFormEntity entity)? customRightView;

  /// 自定义控件的底部控件
  final Widget Function(KqPadFormEntity entity)? customBottomView;

  /// 输入变化回调
  final ValueChanged<String>? onChanged;

  /// 焦点变化
  final Function(bool hasFocus)? onFocusChanged;

  const KqPadEditItemView(
      {Key? key,
      required this.entity,
      this.customLeftView,
      this.customRightView,
      this.customBottomView,
      this.onChanged,
      this.onFocusChanged})
      : super(key: key);

  @override
  KqPadEditItemViewState createState() => KqPadEditItemViewState();
}

class KqPadEditItemViewState extends State<KqPadEditItemView> {
  @override
  void initState() {
    widget.entity.widgetState = this;

    if (widget.entity.controller != null &&
        widget.entity.valueForShow != null) {
      TextFiledUtil.setValue(
          widget.entity.controller!, widget.entity.valueForShow!);
    }
    calTitleWidth();

    super.initState();
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 定位到该条数据，滚动到屏幕中央
  location(ScrollController? scrollController) {
    if (scrollController == null) {
      return;
    }
    //拿到控件的位置
    var position = context.position();
    var dy = position?.dy;
    if (scrollController.hasClients && dy != null) {
      var util = KqScreenUtil();
      var screenHeight = util.screenHeight;
      var targetY = scrollController.offset + dy - screenHeight / 2;
      var maxY = scrollController.position.maxScrollExtent;
      scrollController.jumpTo(max(0, min(targetY, maxY)));
    }
  }

  /// 画笔，用于测量
  TextPainter painter = TextPainter(textDirection: TextDirection.ltr);

  /// 获取文本宽度
  double measureTextWidth(String text, {TextStyle? textStyle}) {
    painter.text = TextSpan(
      text: text,
      style: textStyle,
    );

    painter.layout();
    return painter.width;
  }

  double titleWidth = 0;

  calTitleWidth() {
    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    String titleWidthString = "";
    for (int i = 0; i < (widget.entity.titleFixedWidthCharCount ?? 8); i++) {
      titleWidthString += "中";
    }
    titleWidth = measureTextWidth(titleWidthString, textStyle: titleStyle);
  }

  @override
  void didUpdateWidget(covariant KqPadEditItemView oldWidget) {
    widget.entity.widgetState = this;
    if (widget.entity.controller != null &&
        widget.entity.valueForShow != null) {
      TextFiledUtil.setValue(
          widget.entity.controller!, widget.entity.valueForShow!);
    }
    calTitleWidth();
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    // 背景颜色
    var bgColor = widget.entity.backgroundColor;

    // 计算标题宽度
    TextStyle titleStyle = widget.entity.titleStyle ??
        TextStyle(
            fontSize: widget.entity.titleFontSize ??
                KqPadThemeManager.instance
                    .getConfig()
                    .formConfig
                    .titleFontSize ??
                7.dm,
            color: widget.entity.titleColor ?? KqPadThemeColors.text26);

    bool isHideInputBox =
        KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox !=
                null &&
            KqPadThemeManager.instance.getConfig().formConfig.isHideInputBox!;

    return Visibility(
      visible: widget.entity.visible,
      child: Column(
        children: [
          Container(
            color: bgColor,
            padding: EdgeInsets.only(
                right: widget.entity.paddingHorizontal ??
                    KqPadThemeManager.instance
                        .getConfig()
                        .formConfig
                        .paddingHorizontal ??
                    8.dm,
                top: widget.entity.paddingVertical ?? 0,
                bottom: widget.entity.paddingVertical ?? 0),
            child: Row(
              crossAxisAlignment:
                  widget.entity.multiline && !widget.entity.isEditable()
                      ? CrossAxisAlignment.baseline
                      : CrossAxisAlignment.center,
              textBaseline:
                  widget.entity.multiline && !widget.entity.isEditable()
                      ? TextBaseline.alphabetic
                      : null,
              children: <Widget>[
                /// 是否必填
                Container(
                  alignment: Alignment.centerRight,
                  width: widget.entity.paddingHorizontal ??
                      KqPadThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      8.dm,
                  padding: EdgeInsets.only(right: 1.dm),
                  child: Text(
                    "∗",
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontSize: KqPadThemeManager.instance
                                .getConfig()
                                .formConfig
                                .mustInputFontSize ??
                            7.dm,
                        color: widget.entity.mustInput
                            ? KqPadThemeColors.textRed
                            : widget.entity.mustInputStarColor ??
                                KqPadThemeColors.bgTransparent),
                  ),
                ),

                Container(
                  width: titleWidth + (isHideInputBox ? 0 : 6.dm),
                  padding: EdgeInsets.only(
                      right: isHideInputBox ? 0 : 6.dm, top: 0.5.dm),
                  // width: titleWidth + 6.dm,
                  // padding: EdgeInsets.only(right: 6.dm, top: 0.5.dm),
                  alignment: Alignment.centerRight,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      /// 左边自定义控件
                      /// 自定义布局，来自实体类
                      widget.entity.customLeftView != null
                          ? widget.entity.customLeftView!(widget.entity)
                          : Container(),

                      /// 自定义布局，来自控件
                      widget.customLeftView != null
                          ? widget.customLeftView!(widget.entity)
                          : Container(),

                      if (widget.entity.title.isNotEmpty)
                        Expanded(
                          child: Text(
                            widget.entity.title.fixSoftWrap() ?? '',
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                            textAlign: widget.entity.titleTextAlign,
                            style: titleStyle,
                          ),
                        ),
                    ],
                  ),
                ),

                if (widget.entity.customTitleRightView != null)
                  widget.entity.customTitleRightView!(widget.entity),

                Expanded(
                  /// 输入框
                  child: Container(
                    height:
                        widget.entity.isEditable() && !widget.entity.multiline
                            ? KqPadThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .height ??
                                20.dm
                            : null,
                    constraints: widget.entity.paddingVertical != null
                        ? null
                        : BoxConstraints(
                            minHeight: KqPadThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .height ??
                                20.dm),
                    padding: widget.entity.isEditable()
                        ? EdgeInsets.only(top: 0.5.dm)
                        : EdgeInsets.symmetric(
                            vertical: widget.entity.paddingVertical ?? 7.dm),
                    margin: widget.entity.isEditable()
                        ? EdgeInsets.only(top: 2.dm, bottom: 2.dm)
                        : null,
                    decoration: widget.entity.isEditable() && !isHideInputBox
                        ? KqBoxDecoration(
                            boxShadow: KqPadThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .boderColor !=
                                    null
                                ? null
                                : [
                                    KqBoxShadow(
                                        offset: Offset(0.5.dm, 0.5.dm),
                                        blurRadius: 0,
                                        spreadRadius: 0,
                                        color: const Color(0x80FFFFFF)),
                                    KqBoxShadow(
                                        offset: Offset(0, 0.5.dm),
                                        blurRadius: 3.dm,
                                        spreadRadius: 0,
                                        inset: true,
                                        color: const Color(0xFFB2B7CE)),
                                    KqBoxShadow(
                                        offset: Offset(0.5.dm, 0.5.dm),
                                        blurRadius: 0.5.dm,
                                        spreadRadius: 0,
                                        inset: true,
                                        color: const Color(0xFFC9CCD9)),
                                  ],
                            borderRadius: BorderRadius.circular(
                                KqPadThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .radius ??
                                    1.dm),
                            border: Border.all(
                                color: KqPadThemeManager.instance
                                        .getConfig()
                                        .formConfig
                                        .boderColor ??
                                    KqPadThemeColors.bgTransparent),
                            color: isHideInputBox
                                ? KqPadThemeColors.bgTransparent
                                : KqPadThemeColors.bgWhite,
                          )
                        : null,
                    child: Row(
                      children: [
                        SizedBox(
                          width: 6.dm,
                        ),
                        Expanded(
                          child: KqPadTextFiled(
                            multiline: widget.entity.multiline,
                            maxLines: widget.entity.maxLines,
                            inputType: widget.entity.inputType,
                            showShadow: false,
                            useParentHeight: false,
                            editable: widget.entity.isEditable(),
                            forceShowPlaceHolder:
                                widget.entity.forceShowPlaceHolder,
                            focusNode: widget.entity.focusNode,
                            controller: widget.entity.controller,
                            textColor: widget.entity.contentColor,
                            textInputAction: widget.entity.textInputAction,
                            fontSize: widget.entity.contentFontSize ??
                                KqPadThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .contentFontSize,
                            enableClearButton: widget.entity.enableClearButton,
                            textAlign: widget.entity.contentTextAlign ??
                                (widget.entity.isEditable() && !isHideInputBox
                                    ? TextAlign.start
                                    : TextAlign.end),
                            newValue: widget.entity.valueForShow ?? '',
                            placeHolder: widget.entity.hint,
                            maxCharCount: widget.entity.maxCharCount,
                            onSubmitted: widget.entity.onSubmitted,
                            inputFormatters: widget.entity.inputFormatters,
                            onFocusChanged: (hasFocus) {
                              widget.entity.onFocusChanged?.call(hasFocus);
                              widget.onFocusChanged?.call(hasFocus);
                            },
                            onMonitor: (str) {
                              widget.entity.onMonitor?.call(widget.entity, str);
                            },
                            contentPadding:
                                EdgeInsets.symmetric(vertical: 2.dm),
                            onChanged: (text) {
                              widget.entity.valueForShow = text;
                              widget.entity.valueForSubmit = text;
                              widget.entity.onChanged?.call(text);
                              widget.onChanged?.call(text);
                            },
                          ),
                        ),

                        if (widget.entity.unit.isNullOrEmpty &&
                            widget.entity.isEditable())
                          SizedBox(
                            width: KqPadThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .rightMargin ??
                                6.dm,
                          ),

                        /// 单位
                        Visibility(
                          visible: widget.entity.unit.isNotNullOrEmpty,
                          child: Container(
                              padding: EdgeInsets.only(
                                  left:
                                      widget.entity.isEditable() ? 6.dm : 6.dm,
                                  right: widget.entity.isEditable() &&
                                          widget.entity.customRightView ==
                                              null &&
                                          widget.customRightView == null
                                      ? KqPadThemeManager.instance
                                              .getConfig()
                                              .formConfig
                                              .rightMargin ??
                                          6.dm
                                      : 0),
                              child: Text(
                                widget.entity.unit ?? "",
                                style: TextStyle(
                                  color: widget.entity.unitColor ??
                                      KqPadThemeColors.text59,
                                  fontSize: KqPadThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .unitFontSize ??
                                      7.dm,
                                ),
                              )),
                        ),

                        /// 自定义布局，来自实体类
                        widget.entity.customRightView != null
                            ? widget.entity.customRightView!(widget.entity)
                            : Container(),

                        /// 自定义布局，来自控件
                        widget.customRightView != null
                            ? widget.customRightView!(widget.entity)
                            : Container(),
                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          /// 自定义底部控件，来自实体类
          widget.entity.customBottomView != null
              ? widget.entity.customBottomView!(widget.entity)
              : Container(),

          /// 自定义控件，来自控件
          widget.customBottomView != null
              ? widget.customBottomView!(widget.entity)
              : Container(),

          /// 分割线
          Visibility(
              visible: !widget.entity.forceHideDivider1 &&
                  !widget.entity.isEditable(),
              child: const KqPadDivider()),

          /// 分隔栏
          Visibility(
              visible: !widget.entity.hideDivider2TopMargin &&
                  widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
          Visibility(
              visible: widget.entity.showDivider2, child: const KqPadDivider()),
          Visibility(
              visible: !widget.entity.hideDivider2BottomMargin &&
                  widget.entity.showDivider2,
              child: SizedBox(
                height: 5.dm,
              )),
        ],
      ),
    );
  }
}
